package com.abdosoft.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class AbdoSoftHttpClientMain {

	private Logger logger = LoggerFactory.getLogger(AbdoSoftHttpClientMain.class);
   
	//public static String exBase64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	private  static String tQMZFC ="" ;
	private  static String Sxqdh="";
	private  static String Sflag="";
	private  static String Shttp="";
	private  static String Stoken="";
	
	public static void initHttpClent(String xqdh,String flag , String http,String qmzfc,int timeOut){
		Sxqdh = xqdh;
		Sflag = flag;
		tQMZFC = qmzfc;
		Shttp  = http;
		
		//超时时间
		HttpClentMain.RequestTimeout = timeOut < 20000 ? 20000 : timeOut;
	}
	
	public static void setToken(String  token ){
		Stoken=token;
	} 
	
	/*
	 * 发送请求
	 * 该涵数接口用于已经设置了有效token的情况
	 */
	public static  HashMap<String,String>   httpPost( String ac,String tp , Map<String,String> dataMap){
 		String s= httpPost_(  Sxqdh,  ac,  tp,  Stoken, Sflag,Shttp , dataMap); 
		return  JsonPluginsUtil.jsonToMap(s);
	} 
	
	public static  HashMap<String,String>   httpPost( String ac,String tp,String token, Map<String,String> dataMap){
		
		String s= httpPost_(  Sxqdh,  ac,  tp,  token, Sflag,Shttp , dataMap); 
		return  JsonPluginsUtil.jsonToMap(s);
	}
	 
	public static HashMap<String,String> DecodeData( String dataStr ,  String sign){
	     
		return DecodeData_(   dataStr , Sflag ,   sign);
	}

	
	/*********************************************************************/ 
	/*********************************************************************/ 
	/*
	 * 对外发送 http通知请求  private
	 */
	private  static String  httpPost_(String xqdh,String ac,String tp,String token, String flag,String http ,Map<String,String> dataMap) {
		// TODO Auto-generated method stub
		if(StringUtil.isEmpty(xqdh)  || StringUtil.isEmpty(token)  || StringUtil.isEmpty(http) 
				|| StringUtil.isEmpty(ac)  || StringUtil.isEmpty(tp) ||  dataMap.size() < 1  ){
			return "ERR:参数不足";
		}

		try{
	        //取token
	        {
	    	    //构造请求包
	    	  	Map<String,String> params = new HashMap<String,String>();
	    	  	params.put("sq", "B" + System.currentTimeMillis());/* 访问编号:SQ*/
	        	params.put("ac", ac);/* 协议名称:ac*/
	        	params.put("tp", tp);/* 协议操作:tp*/
	        	params.put("token", token);/* 访问令牌，取令牌协议除外:token*/
	        	params.put("flag", flag);/* 协议内容格式:flag*/
	        	String outData="";
	        	
	        	String dataS=  JsonPluginsUtil.mapToJson(dataMap) ;
	        	
				if ("1".equals(flag)) {/* base64 */
					outData =  Base64.encode(  dataS );
				} else if ("2".equals(flag)) {/* des散列base64 + */
					outData = DESUtil.getDESUtil().encryptRandom(dataS);
				}else  if("3".equals(flag) ){/* 3desbase64 + */
					//outData =   DESUtil.getDESUtil().encrypt( dataS); 
					outData =   DESUtil.getDESUtil().encryptRandom(dataS);
				} else {/* 原始数据 */
					outData = dataS;
				} 
			    String outsign = StringtoSignature(outData,  tQMZFC );
			 
			    params.put("data",outData);/* 协议内容:data*/
			    params.put("sign",outsign);/* 协议内容的签名:sign*/
	        	 
	        	//public   String isok;/* 操作结果:isok*/
	        	//public   String infox;/* 操作结果:infox*/
			    
			    if( http.startsWith("http://")){ 
			      return   SendHttpMain(  xqdh, http,  params  );
			    }else{
			      return 	SendHttpMain(  xqdh, "http://" +  http,  params  );
			    } 
	       } 
		}catch(Exception e){
			e.printStackTrace();
		}  
		
		return "ERR:未知错误";
	}
	 
	private static synchronized String SendHttpMain(String xqdh,String httpaddr,Map<String, String> vars  ) {
 		
		return  httpPost_(  xqdh,  httpaddr,  vars ); 
	}
  
	private static   String httpPost_(String xqdh,String httpaddr,Map<String, String> vars){ 
		String  s ="";
		try {
			//String  s =  com.abdosoft.httpclient.HttpClentMain.post( vars,"http://w.abdosoft.cn/ghome/platform/platformpush.do");
			   s =   HttpClentMain.post( vars,httpaddr);  
    	} catch (Exception e) {
 			System.out.println("发送http请求失败:" + xqdh + "," + httpaddr + "," + vars.toString() );
			// TODO Auto-generated catch block
			 e.printStackTrace(); 
			//记录失败日志 
		}
		
		return s;
	} 

	//解码数据
	private static HashMap<String,String> DecodeData_( String dataStr , String flag , String sign){
    	
    	//签名验证  
		String  ckecksign = StringtoSignature(dataStr, tQMZFC );
		if(!  sign.equals(ckecksign) ){ 
			System.out.println("签名验证失败"); 
			return  null;
		}
    	
    	String data= "";
    	if("1".equals(flag)  ){/* base64 */
			data =  Base64.decode(dataStr); 
		}else if("2".equals(flag) ){/* des散列base64 + */
			data =  DESUtil.getDESUtil().decryptRandom(dataStr); 
		}else  if("3".equals(flag) ){/* 3desbase64 + */
			data =  DESUtil.getDESUtil().decrypt (dataStr); 
		}else{/* 原始数据 */
			data = dataStr;
		} 
    	
		//数据转换
		HashMap<String,String> dataMap= JsonPluginsUtil.jsonToMap(data)  ;
		if(dataMap.size()<1){ 
			System.out.println("格式错误1"); 
			return  dataMap;
		}

		return  dataMap;
		  
    }
 
	//输入一个字符串，生成签名
	private static String StringtoSignature(String msg,String keyroot) {
		// TODO Auto-generated method stub
		//String  keyroot=getSheBeiRootPWD(oper);
		if(keyroot.length() < 256){
			return "";
		} 
		
		String  tempS = "";
		try{
			//byte b_tmp =0;
			int Signature=0;
			if(msg.length()>=0 ){//正常
				for(int x=0;x<msg.length();x=x+1){  
					char  item = msg.charAt(x) ;//取得字符，表示成16进制两字节
					Signature = (Signature + item)%256;
				} 

				int s1= Signature % 23 ;//计算第1位  22,
				int s2= Signature %193; //计算第2位  13,
				int s3= Signature %67;  //计算第3位  5,
				int s4= Signature %139; //计算第4位  67,
				int s5= Signature %151; //计算第5位  55,
				int s6= Signature %256;  //计算第6位  206,

				tempS = tempS + keyroot.substring(s1 , s1 + 1);
				tempS = tempS + keyroot.substring(s2 , s2 + 1);
				tempS = tempS + keyroot.substring(s3 , s3 + 1);
				tempS = tempS + keyroot.substring(s4 , s4 + 1);
				tempS = tempS + keyroot.substring(s5 , s5 + 1);
				tempS = tempS + keyroot.substring(s6 , s6 + 1);

				return tempS;//pWwIdu
			}else{//没有内容

			}
		}catch(Exception e){
			e.printStackTrace();
		} 
		return tempS ;
	}
  
} 
